package backTrack;

import java.util.*;

public class ds216 {
    public static void main(String[] args) {
        System.out.println(combinationSum3(3,9));
    }
    public static List<List<Integer>> combinationSum3(int k, int n) {
        List<List<Integer>> ans = new ArrayList<>();
        List<Integer> path = new ArrayList<>();
        dfs(k, n, ans, path, 1, 0);
        return ans;
    }
    public static void dfs(int k, int n, List<List<Integer>> ans, List<Integer> path, int index, int sum){
        if(path.size() > k)
            return;
        if(path.size() == k && sum == n){
            ans.add(new ArrayList<>(path));
            return;
        }
        for (int i = index; i <= 9 - (k - path.size()) + 1; i++) {
            path.add(i);
            dfs(k, n, ans, path, i + 1, sum + i);
            path.remove(path.size() - 1);
        }
    }
}
